//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.wsd.smartcarwasher.service;

import com.wsd.smartcarwasher.configuration.MyApplicationContextAware;
import com.wsd.smartcarwasher.constans.ResultState;
import com.wsd.smartcarwasher.util.ReturnUtil;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint("/webSocket/{machineId}")
@Component
@Lazy
public class WebSocketServer {
    private static final Logger logger = LoggerFactory.getLogger(WebSocketServer.class);
    private MachineService machineService = (MachineService)MyApplicationContextAware.getApplicationContext().getBean(MachineService.class);
    private static int onlineCount = 0;
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet();
    private Session session;
    private String machineId = "";
    public WebSocketServer() {
    }
    @OnOpen
    public void onOpen(Session session, @PathParam("machineId") String machineId) {
        this.machineId = machineId;
        this.session = session;
        webSocketSet.add(this);
        addOnlineCount();
        logger.info("有新窗口开始监听:" + machineId + ",machineId=" + machineId + ",当前在线人数为" + getOnlineCount());
        this.sendMessage((new JSONObject(ReturnUtil.Success(ResultState.BUILD_WEB_SOCKET_CONNECTION_SUCCESS.getMsg()))).toString());
    }
    @OnClose
    public void onClose() {
        String machineId = this.machineId;
        webSocketSet.remove(this);
        subOnlineCount();
        logger.info(machineId + "连接关闭！当前在线人数为" + getOnlineCount());
    }

    @OnMessage
    public void onMessage(String message) {
        logger.info("收到来自窗口" + this.machineId + "的信息:" + message);
        String returnMessage = this.machineService.receiveMessageFromApp(this.machineId, message);
        this.sendMessage(returnMessage);
    }

    @OnError
    public void onError(Throwable error) {
        logger.error("webSocket发生错误" + this.machineId);
    }

    private void sendMessage(String message) {
        try {
            this.session.getBasicRemote().sendText(message);
        } catch (IOException var3) {
            logger.error("catch error when send message wo app", var3);
        }

    }

    public static void sendInfo(String message, @PathParam("machineId") String machineId) {
        logger.info("推送消息到窗口" + machineId + "，推送内容:" + message);
        Iterator var2 = webSocketSet.iterator();

        while(var2.hasNext()) {
            WebSocketServer item = (WebSocketServer)var2.next();
            if (machineId == null) {
                item.sendMessage(message);
            } else if (item.machineId.equals(machineId)) {
                item.sendMessage(message);
            }
        }

    }

    private static synchronized int getOnlineCount() {
        return onlineCount;
    }

    private static synchronized void addOnlineCount() {
        ++onlineCount;
    }

    private static synchronized void subOnlineCount() {
        --onlineCount;
    }
}

/*
package com.wsd.smartcarwasher.service;

import com.wsd.smartcarwasher.configuration.MyApplicationContextAware;
import com.wsd.smartcarwasher.constans.ResultState;
import com.wsd.smartcarwasher.util.ReturnUtil;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint("/webSocket/{machineId}")
@Component
public class WebSocketServer {
    private static final Logger logger = LoggerFactory.getLogger(WebSocketServer.class);

    private MachineService machineService = MyApplicationContextAware.getApplicationContext().getBean(MachineService.class);

    private static int onlineCount = 0;

    //concurrent包的线程安全Set，存放客户端对应的MyWebSocket对象
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();

    //与客户端的连接会话，通过它给客户端发送数据
    private Session session;

    //接收sid
    private String machineId = "";

    */
/**
     * 连接建立成功调用的方法
     *//*

    @OnOpen
    public void onOpen(Session session, @PathParam("machineId") String machineId) {
        this.machineId = machineId;
        this.session = session;
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //在线数加1
        logger.info("有新窗口开始监听:" + machineId + ",machineId=" + machineId + ",当前在线人数为" + getOnlineCount());
        sendMessage(new JSONObject(ReturnUtil.Success(ResultState.BUILD_WEB_SOCKET_CONNECTION_SUCCESS.getMsg())).toString());
    }

    */
/**
     * 连接关闭调用的方法
     *//*

    @OnClose
    public void onClose() {
        String machineId = this.machineId;
        webSocketSet.remove(this);
        subOnlineCount();
        logger.info(machineId + "连接关闭！当前在线人数为" + getOnlineCount());
    }

    */
/**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     *//*

    @OnMessage
    public void onMessage(String message) {
        logger.info("收到来自窗口" + machineId + "的信息:" + message);
        String returnMessage = machineService.receiveMessageFromApp(machineId, message);
        sendMessage(returnMessage);
    }

    */
/**
     * @param error   错误
     *//*

    @OnError
    public void onError(Throwable error) {
        logger.error("webSocket发生错误" + this.machineId, error);
    }

    */
/**
     * 实现服务器主动推送
     *//*

    private void sendMessage(String message) {
        try {
            this.session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            logger.error("catch error when send message wo app", e);
        }
    }

    */
/**
     * 群发自定义消息
     *//*

    public static void sendInfo(String message, @PathParam("machineId") String machineId) {
        logger.info("推送消息到窗口" + machineId + "，推送内容:" + message);
        for (WebSocketServer item : webSocketSet) {
            //这里可以设定只推送给这个sid的，为null则全部推送
            if (machineId == null) {
                item.sendMessage(message);
            } else if (item.machineId.equals(machineId)) {
                item.sendMessage(message);
            }
        }
    }

    private static synchronized int getOnlineCount() {
        return onlineCount;
    }

    private static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    private static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}
*/
